<?php
namespace app\erp\model;

use think\Model;
use think\Validate;
use traits\model\SoftDelete;
use think\Cache;

class AttrValuedb extends Model
{
    use SoftDelete;

    protected $type = [
        'create_time' => 'timestamp:Y-m-d',
        'delete_time' => 'timestamp:Y-m-d'
    ];
    // 自动完成
    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    protected $name = 'attr_value';

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    protected function setSiteIdAttr($value)
    {
        if (! $value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public function scopeGoodsSku($query, $goods_sku)
    {
        $query->where('goods_sku', 'IN', $goods_sku);
    }
    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset($this->param['delete']) && $this->param['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        /*$query->where('partner_id', PARTNER_ID);
        if (isset($this->param['site_id'])) {
            if ($this->param['site_id'] == 0 || $this->param['site_id'] == '') {
                $query->where('site_id', 'null');
            } else {
                $query->where('site_id', $this->param['site_id']);
            }
        } else {
            if (! empty(SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', 'null');
            }
        }*/
        if (isset($this->param['goods_sku'])) {
            $query->goodsSku($this->param['goods_sku']);
        }
    }

    public function copy()
    {
        $data = $this->cache($this->cache_name('attr_value_select'), 86400, 'attr_value')
            ->select();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            $add_data = array();
            if ($this->param['select_site_id'] == '') {
                $this->param['site_id'] = SITE_ID;
            } else {
                $this->param['site_id'] = $this->param['select_site_id'];
            }
            foreach ($data as $key => $val) {
                unset($val['create_time']);
                $val['site_id'] = $this->param['site_id'];
                $add_data[$key] = $val;
            }
            $this->ajaxDelete();
            $this->isUpdate(false)->saveAll($add_data);
        }
    }

    public function collect()
    {
        $data = $this->cache($this->cache_name('attr_value_select'), 86400, 'attr_value')
            ->select();
        if (! $data->isEmpty()) {
            $data = $data->toArray();
            $add_data = array();
            foreach ($data as $key => $val) {
                unset($val['create_time']);
                unset($val['site_id']);
                $add_data[$key] = $val;
            }
            $this->isUpdate(false)->saveAll($add_data);
        }
    }

    public function ajaxSelect($goods_sku)
    {
        $data = $this->where('goods_sku', $goods_sku)
            ->field('attr_sign,attr_value')
            ->select();
        $new_data = array();
        foreach ($data as $key => $val) {
            $new_data[$val['attr_sign']] = $val['attr_value'];
        }
        return $new_data;
    }
    // 保存第三方采集属性
    public function ajaxApiSaveAll()
    {
        $this->saveAll($this->param, false);
        Cache::clear('attr_value');
        return 'success';
    }
    // 保存
    public function ajaxSave()
    {
        // 找到字段
        $attrdb = new Attrdb();
        $attrdb->param['category_sign'] = $this->param['category_sign3'];
        $get_attr_list = $attrdb->ajaxSelect();
        if ($get_attr_list['count'] == 0) {
            $attrdb->param['category_sign'] = $this->param['category_sign2'];
            $get_attr_list = $attrdb->ajaxSelect();
        }
        if ($get_attr_list['count'] == 0) {
            $attrdb->param['category_sign'] = $this->param['category_sign1'];
            $get_attr_list = $attrdb->ajaxSelect();
        }
        if ($get_attr_list['count'] == 0) {
            // 没有分类属性
            return 'success';
        }
        // 动态验证是否为空
        $rule_arr = array();
        $msg_arr = array();
        $data = array();
        $i = 0;
        foreach ($get_attr_list['data'] as $key => $val) {
            if($this->param['is_zhongdian'] == 2) {
                if ($val['fast_is_must'] == 1) {
                    $rule_arr[$val['attr_sign']] = 'require';
                    $rule_arr[$val['attr_sign'] . '.require'] = '快速上架属性：' . $val['attr_name'] . '不能为空';
                }
            } else {
                if ($val['is_must'] == 1) {
                    $rule_arr[$val['attr_sign']] = 'require';
                    $rule_arr[$val['attr_sign'] . '.require'] = '属性：' . $val['attr_name'] . '不能为空';
                }
            }
            $data[$i]['goods_sku'] = $this->param['goods_sku'];
            $data[$i]['attr_sign'] = $val['attr_sign'];
            if (isset($this->param[$val['attr_sign']])) {
                $this->param[$val['attr_sign']] = str_replace('“','"',$this->param[$val['attr_sign']]);
                if ($val['select_type'] == 2 && $val['value_type'] != 1) {
                    if (is_array($this->param[$val['attr_sign']])) {
                        $data[$i]['attr_value'] = implode(',', $this->param[$val['attr_sign']]);
                        unset($this->param[$val['attr_sign']]);
                        $this->param[$val['attr_sign']] = $data[$i]['attr_value'];
                    } else {
                        $data[$i]['attr_value'] = $this->param[$val['attr_sign']];
                    }
                } else {
                    $data[$i]['attr_value'] = $this->param[$val['attr_sign']];
                }
            } else {
                $data[$i]['attr_value'] = '';
            }
            $i ++;
        }
        if (! empty($rule_arr)) {
            $validate = new Validate($rule_arr, $rule_arr);
            if (! $validate->check($this->param)) {
                return $validate->getError();
            }
        }
        $this->ajaxDelete();
        $this->saveAll($data);
        Cache::clear('attr_value');
        return 'success';
    }
    // 直接删除
    public function ajaxDelete()
    {
        if (isset($this->param['site_id'])) {
            $this->where('site_id', $this->param['site_id'])->delete();
        } else {
            $this->where('goods_sku', $this->param['goods_sku'])->delete();
        }
        Cache::clear('attr_value');
    }
}